<template>
  <div class="online-test-container">
    <!-- 页面标题 -->
    <div class="test-header">
      <div class="header-card">
        <div class="header-actions">
          <el-button @click="goBack" class="back-button">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
        </div>
        <h1 class="test-title">在线测试</h1>
        <p class="test-subtitle">请开始第{{ currentRound }}轮测试 (共{{ totalRounds }}轮)</p>
      </div>
    </div>

    <!-- 测试卡片 -->
    <div class="test-card">
      <!-- 题目头部 -->
      <div class="question-header">
        <div class="question-type-container">
          <div class="orange-bar"></div>
          <div class="question-type-tag">单选题</div>
          <div class="question-text-inline">{{ currentQuestion?.queContent || '加载中...' }}</div>
        </div>
      </div>

      <!-- 题目内容 -->
      <div class="question-content">
        <!-- 选项列表 -->
        <div class="options-container">
          <div
            v-for="(option, index) in currentQuestion?.options || []"
            :key="option.id"
            class="option-item"
            :class="{ selected: selectedAnswer === index }"
            @click="selectAnswer(index)"
          >
            <el-radio :value="index" v-model="selectedAnswer" class="option-radio">
              {{ option.optionText }}
            </el-radio>
          </div>
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="test-footer">
        <el-button
          type="primary"
          size="large"
          :disabled="selectedAnswer === null || loading"
          :loading="loading"
          @click="nextQuestion"
          class="next-button"
        >
          {{ loading ? '提交中...' : '下一题' }}
        </el-button>
      </div>
    </div>

    <!-- 测试完成提示 -->
    <div v-if="isTestComplete" class="completion-overlay">
      <div class="completion-card">
        <div class="completion-bar"></div>
        <div class="completion-content">
          <div class="completion-title">很好!您已完成全部测试</div>
          <div class="completion-subtitle">页面自动跳转 等待时间 {{ countdown }}s</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ArrowLeft } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import * as ExamTasksApi from '@/api/dt/examtasks'

defineOptions({ name: 'OnlineTest' })

const router = useRouter()
const userStore = useUserStore()
const message = useMessage()

interface Emits {
  (e: 'back'): void
}

const emit = defineEmits<Emits>()

// 接收任务ID参数
const props = defineProps<{
  jobId?: number
}>()

// 测试状态
const currentRound = ref(0)
const totalRounds = ref(0)
const currentQuestion = ref<any>(null)
const selectedAnswer = ref<number | null>(null)
const answers = ref<any[]>([])
const isTestComplete = ref(false)
const examId = ref<number | null>(null)
const loading = ref(false)
const countdown = ref(3)
const countdownTimer = ref<NodeJS.Timeout | null>(null)

// 选择答案
const selectAnswer = (index: number) => {
  selectedAnswer.value = index
}

// 开始测试
const startExam = async () => {
  if (!props.jobId) {
    message.error('任务ID不能为空')
    return
  }

  loading.value = true
  try {
    const userId = userStore.user?.id
    const data = await ExamTasksApi.examStart({ userId, jobId: props.jobId })
    currentQuestion.value = data.question
    examId.value = data.examId
    currentRound.value = data.currentStoreIndex
    totalRounds.value = data.totalStores
    selectedAnswer.value = null
  } catch (error) {
    console.error('开始测试失败:', error)
  } finally {
    loading.value = false
  }
}

// 下一题
const nextQuestion = async () => {
  if (selectedAnswer.value === null || !currentQuestion.value) return

  loading.value = true
  try {
    const selectedOption = currentQuestion.value.options[selectedAnswer.value]
    const params = {
      examId: examId.value,
      questionId: currentQuestion.value.id,
      optionId: selectedOption.id,
      flowId: currentQuestion.value.flowId // 默认流程ID
    }
    const data = await ExamTasksApi.examubmitAndNext(params)
    // 保存当前答案
    answers.value.push({
      questionId: currentQuestion.value.id,
      optionId: selectedOption.id,
      optionText: selectedOption.optionText
    })
    // 检查测试状态
    if (data.status === 'completed') {
      // 测试完成
      currentRound.value = data.currentStoreIndex
      totalRounds.value = data.totalStores
      isTestComplete.value = true
      console.log('测试完成，答案：', answers.value)
      startCountdown()
    } else if (data && data.question) {
      // 还有下一题
      currentRound.value = data.currentStoreIndex
      totalRounds.value = data.totalStores
      currentQuestion.value = data.question
      selectedAnswer.value = null
    } else {
      // 没有下一题，测试完成
      isTestComplete.value = true
      console.log('测试完成，答案：', answers.value)
      startCountdown()
    }
  } catch (error) {
    console.error('提交答案失败:', error)
  } finally {
    loading.value = false
  }
}

// 倒计时功能
const startCountdown = () => {
  countdown.value = 3
  countdownTimer.value = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      goBack()
      router.push({ path: '/dt/dtuserexam', query: { jobId: props.jobId } })
    }
  }, 1000)
}

// 返回功能
const goBack = () => {
  // 清除倒计时
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
    countdownTimer.value = null
  }
  emit('back')
}

// 初始化
onMounted(() => {
  startExam()
})

// 清理倒计时
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
})
</script>

<style scoped>
.online-test-container {
  position: relative;
}

.test-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
}

.header-card {
  background: white;
  border-radius: 6px;
  padding: 12px 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  text-align: center;
  position: relative;
  width: 100%;
}

.header-actions {
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
}

.back-button {
  color: #6b7280;
  font-size: 14px;
  padding: 4px 8px;
}

.back-button:hover {
  color: #3b82f6;
}

.test-title {
  font-size: 16px;
  font-weight: 700;
  color: #3b82f6;
  margin: 0 0 4px 0;
}

.test-subtitle {
  font-size: 12px;
  color: #1e293b;
  margin: 0;
}

.test-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  max-width: 100%;
  margin: 0 auto;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.question-header {
  margin-bottom: 16px;
}

.question-type-container {
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
}

.orange-bar {
  width: 3px;
  height: 20px;
  background: #f97316;
  border-radius: 2px;
}

.question-type-tag {
  background: #dbeafe;
  color: #1e40af;
  padding: 3px 10px;
  border-radius: 10px;
  font-size: 12px;
  font-weight: 500;
}

.question-text-inline {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
}

.question-content {
  margin-bottom: 20px;
}

.options-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 16px;
}

.option-item {
  padding: 10px 14px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: white;
}

.option-item:hover {
  border-color: #3b82f6;
  background: #f8fafc;
}

.option-item.selected {
  border-color: #3b82f6;
  background: #eff6ff;
}

.option-radio {
  width: 100%;
}

.option-radio :deep(.el-radio__label) {
  font-size: 13px;
  color: #374151;
  font-weight: 400;
}

.option-radio :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #3b82f6;
  border-color: #3b82f6;
}

.test-footer {
  text-align: center;
}

.next-button {
  padding: 8px 24px;
  font-size: 13px;
  font-weight: 500;
  border-radius: 4px;
  min-width: 80px;
}

.next-button:disabled {
  background-color: #9ca3af;
  border-color: #9ca3af;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .online-test-container {
    padding: 16px;
  }

  .test-card {
    padding: 12px;
  }

  .header-card {
    width: 100%;
    padding: 10px 12px;
  }

  .test-title {
    font-size: 14px;
  }

  .test-subtitle {
    font-size: 11px;
  }

  .header-actions {
    left: 12px;
  }

  .question-text {
    font-size: 15px;
  }

  .progress-widget {
    right: 16px;
    padding: 16px 12px;
  }

  .progress-percentage {
    font-size: 20px;
  }
}

/* 完成提示样式 */
.completion-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.completion-card {
  background: white;
  border-radius: 8px;
  padding: 24px 32px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  text-align: center;
  position: relative;
  min-width: 300px;
  max-width: 400px;
}

.completion-bar {
  position: absolute;
  left: 0;
  top: 0;
  width: 4px;
  height: 100%;
  background: #3b82f6;
  border-radius: 0 2px 2px 0;
}

.completion-content {
  margin-left: 16px;
}

.completion-title {
  font-size: 18px;
  font-weight: 700;
  color: #3b82f6;
  margin-bottom: 12px;
}

.completion-subtitle {
  font-size: 14px;
  font-weight: 500;
  color: #dc2626;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .completion-card {
    margin: 20px;
    padding: 20px 24px;
    min-width: 280px;
  }

  .completion-title {
    font-size: 16px;
  }

  .completion-subtitle {
    font-size: 13px;
  }
}
</style>
